package ecom.servlets;
//
import ecom.beans.*;
import ecom.beans.account.AccountEntityFacadeRemote;
import ecom.beans.address.AddressEntityFacadeRemote;
import ecom.beans.cart.CartSessionRemote;
import ecom.beans.customer.CustomerEntity;
import ecom.beans.customer.CustomerEntityFacadeRemote;
import ecom.beans.dish.DishEntityFacadeRemote;
import ecom.beans.menuorder.MenuOrderEntityFacadeRemote;
import ecom.beans.store.StoreEntityFacadeRemote;

import java.io.IOException;
import java.io.PrintWriter;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.naming.NamingException;
import javax.transaction.UserTransaction;

public class LoginServlet extends HttpServlet {

  /**
     * Serializable class uid.
     */
    private static final long serialVersionUID = 6893863749912962928L;

    private Context initialContext;
    private UserTransaction utx;
    private CustomerEntityFacadeRemote customerEntityFacade;
    

    
    private int Login(PrintWriter out,  int numChamp){//accountType = 1 for a customer, 2 for a restaurant
		out.println("E-mail &nbsp; <input type=\"text\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
	 	out.println("Mot de passe &nbsp; <input type=\"password\" name=\"T"+(numChamp++)+"\" size=\"20\"><br>");
	 	
	 	return numChamp;
	}
    
    /**
     * validate of email and pwd
     * @param email
     * @param pwd
     * @return
     */
    private String ValidateData(String email, String pwd) {
		String error = "";

		// Validate fields
		if ((email == null) || (email.length() == 0) || (email.length() > 255)) {
			error = error + "cette adresse email est incorrecte.<br>";
			return error;
		}

		if ((pwd == null) || (pwd.length() == 0) || (pwd.length() > 20)) {
			error = error + "Ce mot de passe n est pas bon.<br>";
			return error;
		}
		return error;

	}
    public void menuLogged(CustomerEntity loggedCustomer , PrintWriter out){
    	String st = "<p class='menubar'><a href='store'>Informations de votre compte</a>&nbsp;|&nbsp;" +
    									"<a href='majcustomer'>Modifier votre compte client</a>" +
    									"<a href='store'>Liste des plats</a>&nbsp;|&nbsp;" +
    									"<a href='store'>Gerer votre panier</a>&nbsp;|&nbsp;" +
    									"<a href='store'>Supprimer votre compte</a>&nbsp;|&nbsp;" +
    									"<a href='store'>Se deconnecter</a>&nbsp;|&nbsp;" +
    									"</p>";
    	out.println(st);
    	
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    	doGet( request, response);
    }
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    	initialContext = null;
        utx = null;
        customerEntityFacade = null;

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<link type=\"text/css\" href=\"../ow_jonas.css\" rel=\"stylesheet\" id=\"stylesheet\">");
        out.println("<title>");
        out.println("Admin Servlet</title>");
        out.println("</head>");
        out.println("<body style=\"background : white; color : black;\">");
        
        
        int numChamp;
        String login = request.getParameter("Login");
        //out.println("Login : "+login);
        if(login != null)
        {
        	numChamp = 0 ;//initialisation
        	String email = request.getParameter("T"+numChamp++);
			String pwd = request.getParameter("T"+numChamp++);
			String error = this.ValidateData(email, pwd);
			if(error.equals("")){
				System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory");
		        
		         try
		         {
		        	 initialContext = new InitialContext();
		        	 //out.println("Creation of initialContext...OK   ");
		         } 
		         catch (Exception e)
		         {
		            System.err.println("Cannot get initial context for JNDI: " + e);
		            System.exit(2);
		         }

		        try
		        {
		            utx = (UserTransaction) initialContext.lookup("javax.transaction.UserTransaction");
		            //out.println("Creation of utx...OK   ");
		        }
		        catch (NamingException e) 
		        {
		            out.println("Cannot lookup UserTransaction: " + e);
		            System.exit(2);
		        }

				try
		        {
		            customerEntityFacade = (CustomerEntityFacadeRemote) initialContext.lookup("ecom.beans.customer.CustomerEntityFacade" + "_" + CustomerEntityFacadeRemote.class.getName() + "@Remote");
		            //out.println("Creation of customerEntityFacade...OK     ");
		        } 
		        catch (NamingException e)
		        {
		            out.println("Cannot get customerEntityFacade : " + e);
		            System.exit(2);
		        }
		        	
		        if(customerEntityFacade.findCustomerEmail(email) == true){
		        	 CustomerEntity loggedCustomer = customerEntityFacade.loginCustomer(email, pwd);
		             if (loggedCustomer != null){
		            	 //out.println("Vous etes maintenant connecte en tant que " + loggedCustomer.getFirstname() + " " + loggedCustomer.getLastname());
		            	 HttpSession session = request.getSession(true);
		            	 session.setAttribute("login_id", loggedCustomer.getId() );
		            	 session.setAttribute("login_Firstname", loggedCustomer.getFirstname());
		            	 session.setAttribute("login_Lastname", loggedCustomer.getLastname());
		            	 response.sendRedirect("/ecom/login.jsp");//pour revenir a la page indiquer
		            	
		            	 menuLogged(loggedCustomer , out);
		            	 
		             
		             } 
		             else{
		            	 out.println("Le mot de passe est incorrect.");
		            	 
		             }
		        }
		        else{
		        	out.println("L email entre ne correspond a aucun compte client.");
		        }

			}
			else{
				out.println(error);
			}
				
        }
       /* else
        {
        	out.println("<form method=\"get\" action=\"\" name=\"form1\">");
        	numChamp = 0;
        	Login( out, numChamp);
        	out.println("<input type=\"submit\" value=\"Envoyer\" name=\"login\"><br>");
        	out.println("</form>");
        }
        */
      
        out.println("</body>");
        out.println("</html>");
    }
}
